<?php

namespace StarCloud\Library;

use Phalcon\Di;
use StarCloud\Models\Famy\Microapp;

class KuaishouPay
{
    protected $app_id = "";
    protected $app_secret = "";
    public function __construct($appId)
    {
        $app = Microapp::findFirstByMicroappId($appId);
        $this->app_id = $app->getMicroappId();
        $this->app_secret = $app->getMicroappSecret();
    }

    public function queryOrder($out_order_no, $accessToken)
    {
        $data = [
            "out_order_no" => $out_order_no,
        ];

        $getdata = [
            "app_id"=>$this->app_id,
            "access_token"=>"$accessToken",
        ];

        $data["sign"] = $this->getSignContent($getdata ,$data, $this->app_secret);	//这里写了一个签名的方法
        $url = 'https://open.kuaishou.com/openapi/mp/developer/epay/query_order?' . http_build_query($getdata);
        $ret = $this->curl_raw_post($url,$data);
        $arr = json_decode($ret,true);
        return $arr;
    }
    public function createOrder($out_trade_no, $openid, $total_amount, $body, $type, $access_token, $isIos = false)
    {
        $msectime = time();
        if ($isIos) {
            $data = [
                "out_order_no"=>"$out_trade_no",
                "open_id"=>"$openid",
                "order_amount"=>$total_amount,
                "user_pay_amount"=>$total_amount,
                "subject"=>"$body",
                "detail"=>"$body",
                "type"=>$type,
                "expire_time"=>500,
                "attach"=>$msectime,//开发者自定义字段，回调原样回传.注：1汉字=2字符；勿回传敏感信息
                "notify_url"=>"https://api.doumvip.com/api/order/kuaishoupay_callback",
            ];
        } else {
            $data = [
                "out_order_no"=>"$out_trade_no",
                "open_id"=>"$openid",
                "total_amount"=>$total_amount,
                "subject"=>"$body",
                "detail"=>"$body",
                "type"=>$type,
                "expire_time"=>500,
                "attach"=>$msectime,//开发者自定义字段，回调原样回传.注：1汉字=2字符；勿回传敏感信息
                "notify_url"=>"https://api.doumvip.com/api/order/kuaishoupay_callback",
            ];
        }

        Di::getDefault()->get('logger')->info("order data is" . json_encode($data));
        $getdata = [
            "app_id"=>$this->app_id,
            "access_token"=>"$access_token",
        ];

        $data["sign"] = $this->getSignContent($getdata ,$data, $this->app_secret);	//这里写了一个签名的方法
        $orderinfo= $this->getorderinfo($getdata ,$data, $isIos);
        $orderinfo["out_order_no"]=$out_trade_no;

        return $orderinfo;
    }

    /**
     * 快手担保支付签名处理
     * @param $params
     * @param $charset
     * @return string
     */
    private function getSignContent($query ,$postData , $app_secret) {
        unset($query['access_token']);
        $arr = array_merge($query, $postData);
        // return $arr;
        foreach ($arr as $k => $item) {
            if (empty($item)) {
                unset($arr[$k]);
            }
        }
        ksort($arr, 2);
        $str = '';
        foreach ($arr as $k => $v) {
            $str .= $k . '=' . $v . '&';
        }
        $str = substr($str, 0, strlen($str) - 1);
        $md5 = $str .  $app_secret;
        return md5($md5);

    }



    public function getorderinfo( $getData,$data, $isIos = false){

        if ($isIos) {
            $url = 'https://open.kuaishou.com/openapi/mp/developer/epay/iap/create_order?' . http_build_query($getData);

        } else {
            $url = 'https://open.kuaishou.com/openapi/mp/developer/epay/create_order?' . http_build_query($getData);

        }
        $ret = $this->curl_raw_post($url,$data);
        $arr = json_decode($ret,true);
        return $arr;
    }

    public function curl_raw_post($url,$post_data = array()){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post_data));
        curl_setopt($ch,CURLOPT_HTTPHEADER,array('Content-Type: application/json'));
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }
}